package com.nulp.psycho.db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.nulp.psycho.db.ConnectionManager;
import com.nulp.psycho.db.dao.BaseDao;
import com.nulp.psycho.db.mapping.Converter;
import com.nulp.psycho.db.model.Answer;

public class AnswerDao implements BaseDao  {
	
	private final String ADD_ANSWER = "INSERT INTO answer (text) VALUES (?)";
	private final String GET_ANSWER_BY_ID = "SELECT * FROM answer WHERE id = ?";
	private final String REMOVE_ANSWER = "DELETE FROM answer WHERE id = ?";
	private final String UPDATE_ANSWER = "UPDATE answer SET text=? WHERE id = ?";
	
	@Override
	public <T> void create(T element) {
		Answer temp = (Answer) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(ADD_ANSWER)) {
			preparedStatement.setString(1, temp.getText());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T read(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		Answer answer = null;
		try (PreparedStatement statement = connection
				.prepareStatement(GET_ANSWER_BY_ID)) {
			statement.setInt(1, id);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				answer = Converter.<Answer> fromResaultSetToObject(rs,
						Answer.class);
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) answer;		
	}

	@Override
	public void delete(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(REMOVE_ANSWER)) {
			preparedStatement.setInt(1, id);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@Override
	public <T> void update(T element) {
		Answer temp = (Answer) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(UPDATE_ANSWER)) {
			preparedStatement.setInt(2, temp.getId());
			preparedStatement.setString(1, temp.getText());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}
	
}
